package toDo.app.models;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

import toDo.app.R;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Point;
import android.location.Address;
import android.location.Geocoder;
import android.view.MotionEvent;
import android.widget.Toast;

import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapActivity;
import com.google.android.maps.MapView;
import com.google.android.maps.Overlay;

public class MapLocation extends Overlay {
	private GeoPoint point;
	private MapActivity map;
	private ToDoListItem item;

	public MapLocation(MapActivity map, ToDoListItem item) {
		this.map = map;
		this.item = item;
		Geocoder geoCoder = new Geocoder(map, Locale.getDefault());
		try {
			List<Address> addresses = geoCoder.getFromLocationName(item.location, 5);
			if (addresses.size() > 0) {
				point = new GeoPoint((int) (addresses.get(0).getLatitude() * 1E6), (int) (addresses.get(0)
						.getLongitude() * 1E6));
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	@Override
	public boolean draw(Canvas canvas, MapView mapView, boolean shadow, long when) {
		super.draw(canvas, mapView, shadow);

		// ---translate the GeoPoint to screen pixels---
		Point screenPts = new Point();
		mapView.getProjection().toPixels(point, screenPts);

		// ---add the marker---
		Bitmap bmp = BitmapFactory.decodeResource(mapView.getResources(), R.drawable.marker);
		canvas.drawBitmap(bmp, screenPts.x, screenPts.y - 50, null);
		return true;
	}

	@Override
	public boolean onTouchEvent(MotionEvent event, MapView mapView) {
		// ---when user lifts his finger---
		if (event.getAction() == 1) {
			GeoPoint p = mapView.getProjection().fromPixels((int) event.getX(), (int) event.getY());

			Geocoder geoCoder = new Geocoder(map.getBaseContext(), Locale.getDefault());
			try {
				List<Address> addresses = geoCoder
						.getFromLocation(p.getLatitudeE6() / 1E6, p.getLongitudeE6() / 1E6, 1);

				if (addresses.size() > 0) {
					String add = "";
					for (int i = 0; i < addresses.get(0).getMaxAddressLineIndex(); i++)
						add += addresses.get(0).getAddressLine(i) + "\n";
					if (item.itemName != null)
						add += "Name: " + item.itemName + "\n";
					if (item.description != null)
						add += "Description: " + item.description + "\n";
					Toast.makeText(map.getBaseContext(), add, Toast.LENGTH_SHORT).show();
				}

			} catch (IOException e) {
				e.printStackTrace();
			}
			return true;
		} else
			return false;
	}

	public GeoPoint getGeoPoint() {
		return point;
	}
}
